package cn.edu.swu.io;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ImageManager {
    //图片管理
    private Map<String, String> imageMap = new HashMap<>();//Map列表储存图片信息
    private SimpleDateFormat timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void downloadImage(String url) throws IOException {
//        String imageName = url.substring(url.lastIndexOf("/") + 1);//截取到图片名
        //判断URL中的非法符号
        int paramIndex = url.lastIndexOf("?");
        if (paramIndex != -1) {
            url = url.substring(0,paramIndex);
        }
        String imageName = url.substring(url.lastIndexOf("/") + 1);
        String savePath = "images/" + imageName;
        FileUtils.ensureDirectoryExists("images");
        FileUtils.saveImage(url, savePath);//下载图片，并将信息加入集合
        //记录日志
        String log = timeStamp.format(new Date()) + "  Downloaded: " + url + " -> " + savePath;
        FileUtils.appendLog(log);
        //将图片信息放入Map
        imageMap.put(imageName, savePath);
        System.out.println("图片下载成功!图片名：" + imageName);
    }

    //遍历集合，打印已下载图片列表
    public void listImages() {
        if (imageMap.isEmpty()) {
            System.out.println("=== 暂无下载的图片 ===");
            return;
        }
        System.out.println("=== 已下载图片列表 ===");
        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            System.out.println("图片名：" + entry.getKey() + " 本地路径：" + entry.getValue());
        }
    }
    //根据名称查找图片路径
    public void searchImage(String imageName) {
        if (imageMap.containsKey(imageName)) {
            System.out.println("本地路径：" + imageMap.get(imageName));
        } else{
            System.out.println("未找到该图片");
        }
    }
}
